// 添加商品
const express = require('express')
const router = express.Router()
const multer =require('multer')
const path = require('path')
const  filepath  = './uploads/'
const  tianjiashangping = require('../../db/tianjiashangping')


const upload = multer({storage:multer.diskStorage({
    destination(req,res,cd){
        cd(null,filepath)

    },
    filename(req,file,cd){
        let suffix = path.extname(file.originalname)
        let filename = +new Date() + Math.floor(Math.random()*899999)+100000+suffix
        cd(null,filename)
    }
})})

// 商品添加

router.post('/tjsp',upload.single('imgpath'),(req,res)=>{
    // 接收数据
    let {name, price, spec: specifications, kind, catname} =req.body

    // 获取图片路径  并将\ 替换为/
    let imgpath =req.file.path.replace(/\\/g,'/')
    // 存入数据库
    tianjiashangping.findOne({name},(err,docs)=>{
        if(err){
            throw new Error(err)
        }
        if(docs){
            res.json({
                error_code:1,
                msg:'商品已经存在'
            })
            return
        }
        tianjiashangping.insertMany({
            name,
            price,
            catname,
            specifications:specifications.join('====='),
            kind:kind.join('====='),
            imgpath
        },(err,docs)=>{
            if(err){
                throw new Error(err)
            }
            res.json({
                error_code:0,
                msg:'商品添加成功'
            })
        })
    })

})

module.exports = router